package org.mch.swingm.ext;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Insets;
import java.awt.SystemColor;

import javax.swing.JPanel;
import javax.swing.border.LineBorder;

import org.mch.swingm.core.MLabel;
import org.mch.swingm.core.MTextField;
import org.mch.swingm.itf.IMExtComponent;
import org.mch.swingm.obj.MItem;
import org.mch.swingm.text.document.IntegerDocument;
import org.mch.swingm.text.document.LongDocument;

/**
 * 描述：扩展 TextField；<BR/>
 * 
 * @author MCH；Date：2008-06-18；<BR/>
 *
 */
public class METextField extends JPanel implements IMExtComponent {
	private static final long serialVersionUID = 1822768862585356326L;
	private MLabel label;
	private MTextField textField;
	private MItem item;

	public METextField(String name) {
		super();
		this.item = new MItem(name, name, true, true);
		initGUI();
	}

	public METextField(String key, String name) {
		super();
		this.item = new MItem(key, name, true, true);
		initGUI();
	}

	public METextField() {
		super();
		this.item = new MItem("", "");
		initGUI();
	}

	public METextField(MItem item) {
		super();
		this.item = item;
		initGUI();
	}

	private void initGUI() {
		setBorder(new LineBorder(Color.LIGHT_GRAY));
		setLayout(new BorderLayout(0, 0));
		add(getLabel(), BorderLayout.WEST);
		add(getComponent(), BorderLayout.CENTER);

	}

	public MLabel getLabel() {
		if (label == null) {
			label = new MLabel(getItem().getName());
			label.setPreferredSize(new Dimension(100, 0));
			label.setToolTipText(getItem().getHint());
			label.setFont(new Font("宋体", Font.PLAIN, 13));
			label.setBorder(new LineBorder(SystemColor.controlShadow));
			// label.setPreferredSize(new Dimension(100, 23));// 设置Label的绝对宽与高
		}
		return label;
	}

	public MTextField getComponent() {
		if (textField == null) {
			textField = new MTextField();
			textField.setFont(new Font("宋体", Font.PLAIN, 13));
			textField.setMargin(new Insets(0, 0, 0, 0));
			textField.setBorder(null);
			textField.setPreferredSize(new Dimension(getItem().getTextwidth(), 23));
			textField.setEditable(getItem().getIsedit().booleanValue());
		}
		return textField;
	}

	public void setTextType(String type) {
		if ("int".equalsIgnoreCase(type) || "integer".equalsIgnoreCase(type)) {
			getComponent().setDocument(new IntegerDocument());
		} else if ("long".equalsIgnoreCase(type)) {
			getComponent().setDocument(new LongDocument());
		}
	}

	@Override
	public void setValue(Object s) {
		if (s == null) {
			getComponent().setText("");
		} else {
			if (s instanceof String) {
				getComponent().setText((String) s);
			} else {
				getComponent().setText(s.toString());
			}
		}
	}

	public String getValue() {
		return getComponent().getText();
	}

	public MItem getItem() {
		return item;
	}

	public String getKey() {
		return getItem().getKey();
	}

}
